#include "RingQueue.hpp"
#include "Task.hpp"
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <ctime>
#include <cstdlib>

std::string SelfName()
{
    char name[128];
    snprintf(name,sizeof name,"thread[%d]",pthread_self());
    return name;
}

void *ProductorRoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (true)
    {
        int x = rand() % 10;
        int y = rand() % 5;
        char op = oper[rand() % oper.size()];
        Task t(x, y, op, mymath);

        ringqueue->push(t);
        std::cout << SelfName() << ", 生产者派发了一个任务：" << t.toTeskString() << std::endl;
        //sleep(1);
    }
}

void *ConsumerRoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (true)
    {
        Task t;
        ringqueue->pop(&t);
        std::string result = t();
        std::cout << SelfName() << ", 消费者消费了一个任务：" << result << std::endl;
    }
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid() ^ pthread_self());

    // RingQueue<int>* rq = new RingQueue<int>();
    RingQueue<Task> *rq = new RingQueue<Task>();

    pthread_t c[8], p[4];
    for (int i = 0; i < 4; i++)
    {
        pthread_create(p + i, nullptr, ProductorRoutine, rq);
    }

    for (int i = 0; i < 8; i++)
    {
        pthread_create(c + i, nullptr, ConsumerRoutine, rq);
    }

    for (int i = 0; i < 4; i++)
    {
        pthread_join(p[i], nullptr);
    }

    for (int i = 0; i < 8; i++)
    {
        pthread_join(c[i], nullptr);
    }

    delete rq;

    return 0;
}
